const fs = require("fs");
const path = require("path");
const os = require("os");

const parse = function parse(src) {
  const obj = {};

  src
    .toString()
    .split("\n")
    .forEach((item) => {
      const keyValueArr = item.split("=");
      const key = keyValueArr[0];
      const val = keyValueArr[1] || "";
      obj[key] = val;
    });

  return obj;
};

const resolveHome = (envPath) => {
  return envPath[0] === "~"
    ? path.join(os.homedir(), envPath.slice(1))
    : envPath;
};

const config2 = function (options) {
  console.log("os==", os.homedir());
  let envPath = path.resolve(process.cwd(), ".env");

  let encoding = "utf8";

  let debug = false;
  if (options) {
    if (options.path !== null) {
      envPath = resolveHome(options.path);
    }
    if (options.encoding !== null) {
      encoding = options.encoding;
    }

    if (options.debug !== null) {
      debug = true;
    }
  }

  const envContent = parse(fs.readFileSync(envPath, encoding), { debug });

  Object.keys(envContent).forEach((key) => {
    if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
      process.env[key] = envContent[key];
    }
  });
  //   console.log(process.env);
  return envContent;
};

const envConfig = config2({
  path: "~/zhen/work/study-demo/dotenv/examples/.env",
  debug: true,
});

console.log(envConfig);
